package com.huihe.framework.handler;

import com.alibaba.fastjson2.JSON;
import com.huihe.common.constant.HttpStatusConstants;
import com.huihe.common.entity.AjaxResult;
import com.huihe.common.utils.ServletUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

@Slf4j
@Component
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint, Serializable {

    /**
     * 处理未认证请求
     * @param request 请求
     * @param response 响应
     * @param authException 触发认证流程的异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        int code = HttpStatusConstants.UNAUTHORIZED;
        String msg = "请求访问:" + request.getRequestURI() + ",认证失败，无法访问系统资源";
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
        //log.error("认证失败原因:"+authException.getMessage(),authException);
    }
}
